package com.ksyun.seckill.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;



@Slf4j
public class GenerateVerifyUtil {

    /**
     * 生成验证码图片
     * @param httpServletResponse
     */
    public static void generateVerifyCode(HttpServletResponse httpServletResponse,String captcha){
        int width = 200;
        int height = 60;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) image.getGraphics();
        // 设置背景色为白色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        // 设置字体和颜色
        g2d.setFont(new Font("Tahoma", Font.BOLD, 40));
        Random random = new Random();
        for (int i = 0; i < captcha.length(); i++) {
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            g2d.setColor(color);
            g2d.drawString(String.valueOf(captcha.charAt(i)), 40 * i + 10, 45);
        }
        g2d.dispose();
        httpServletResponse.setContentType("image/png");
        try {
            ImageIO.write(image, "png", httpServletResponse.getOutputStream());
        } catch (IOException e) {
            log.error("生成验证码的时候出现异常:{}",e.getMessage());
        }
    }
}
